<template>
  <!-- 保持原模板内容不变 -->
  <div id="addQuestionView">
    <el-form :model="form" label-position="left">
      <el-form-item label="标题" prop="title" label-width="70px">
        <el-input v-model="form.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="标签" prop="tags" label-width="70px">
        <el-select
          v-model="form.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请选择或输入标签"
          style="width: 100%"
        >
          <el-option
            v-for="item in tags"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="题目内容" prop="content" label-width="70px">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="5"
          placeholder="请输入题目内容"
          @input="handleContentChange"
        />
      </el-form-item>
      <el-form-item label="答案" prop="answer" label-width="70px">
        <el-input
          v-model="form.answer"
          type="textarea"
          :rows="5"
          placeholder="请输入答案"
          @input="handleAnswerChange"
        />
      </el-form-item>
      <el-form-item label="判题配置">
        <el-space direction="vertical" style="min-width: 480px">
          <el-form-item label="时间限制" prop="judgeConfig.timeLimit">
            <el-input-number
              v-model="form.judgeConfig.timeLimit"
              placeholder="请输入时间限制"
              :min="0"
              size="large"
            />
          </el-form-item>
          <el-form-item label="内存限制" prop="judgeConfig.memoryLimit">
            <el-input-number
              v-model="form.judgeConfig.memoryLimit"
              placeholder="请输入内存限制"
              :min="0"
              size="large"
            />
          </el-form-item>
          <el-form-item label="堆栈限制" prop="judgeConfig.stackLimit">
            <el-input-number
              v-model="form.judgeConfig.stackLimit"
              placeholder="请输入堆栈限制"
              :min="0"
              size="large"
            />
          </el-form-item>
        </el-space>
      </el-form-item>
      <el-form-item label="测试用例配置">
        <div style="margin-top: 32px">
          <el-button
            type="success"
            @click="handleAdd"
            style="position: absolute; top: 50px; left: -100px"
          >
            新增测试用例
          </el-button>
        </div>
        <div v-for="(judgeCaseItem, index) of form.judgeCase" :key="index">
          <el-space
            direction="vertical"
            style="min-width: 640px; margin-bottom: 20px"
          >
            <el-form-item :label="`输入用例-${index + 1}`">
              <el-input
                v-model="judgeCaseItem.input"
                type="textarea"
                :rows="3"
                placeholder="请输入测试输入用例"
                @input="handleInputChange(index)"
                style="width: 1200px"
              />
            </el-form-item>
            <el-form-item :label="`输出用例-${index + 1}`">
              <el-input
                v-model="judgeCaseItem.output"
                type="textarea"
                :rows="3"
                placeholder="请输入测试输出用例"
                style="width: 1200px"
              />
            </el-form-item>
            <el-button type="danger" @click="handleDelete(index)">
              删除
            </el-button>
          </el-space>
        </div>
      </el-form-item>
      <div style="margin-top: 16px" />
      <el-form-item>
        <el-button type="primary" style="min-width: 200px" @click="doSubmit">
          提交
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { QuestionControllerService } from "../../../xiongoj_backendapi";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
//添加标签
interface Tag {
  label: string;
  value: string;
}
const tags = ref<Tag[]>([]);
const fetchTags = async () => {
  try {
    const response = await TagsControllerService.getAllTagListUsingGet();
    if (response.code === 0) {
      const tagNames = response.data;
      tags.value = tagNames.map((tagName: string) => ({
        label: tagName,
        value: tagName,
      }));
    } else {
      ElMessage.error("获取标签列表失败: " + response.message);
    }
  } catch (error) {
    ElMessage.error("获取标签列表失败，请稍后重试");
  }
};

const route = useRoute();
// 如果页面地址包含 update，视为更新页面
const updatePage = route.path.includes("update");
import { TagsControllerService } from "../../../backendapi";
let form = ref({
  title: "",
  tags: [],
  answer: "",
  content: "",
  judgeConfig: {
    memoryLimit: 1000,
    stackLimit: 1000,
    timeLimit: 1000,
  },
  judgeCase: [
    {
      input: "",
      output: "",
    },
  ],
});

/**
 * 新增判题用例
 */
const handleAdd = () => {
  form.value.judgeCase.push({
    input: "",
    output: "",
  });
};

/**
 * 根据题目 id 获取老的数据
 */
const loadData = async () => {
  const id = route.query.id;
  if (!id) {
    return;
  }
  const res = await QuestionControllerService.getQuestionByIdUsingGet(
    id as any
  );
  if (res.code === 0) {
    form.value = res.data as any;
    // json 转 js 对象
    if (!form.value.judgeCase) {
      form.value.judgeCase = [
        {
          input: "",
          output: "",
        },
      ];
    } else {
      form.value.judgeCase = JSON.parse(form.value.judgeCase as any);
    }
    if (!form.value.judgeConfig) {
      form.value.judgeConfig = {
        memoryLimit: 1000,
        stackLimit: 1000,
        timeLimit: 1000,
      };
    } else {
      form.value.judgeConfig = JSON.parse(form.value.judgeConfig as any);
    }
    if (!form.value.tags) {
      form.value.tags = [];
    } else {
      form.value.tags = JSON.parse(form.value.tags as any);
    }
  } else {
    ElMessage.error("加载失败，" + res.message);
  }
};

onMounted(() => {
  loadData();
  fetchTags();
});

/**
 * 删除判题用例
 */
const handleDelete = (index: number) => {
  form.value.judgeCase.splice(index, 1);
};

// 处理题目内容输入的换行转换为 \n
const handleContentChange = (e: any) => {
  if (e && e.target) {
    form.value.content = e.target.value
      .replace(/\r\n/g, "\n")
      .replace(/\r/g, "\n");
  }
};

// 处理答案输入的换行转换为 \n
const handleAnswerChange = (e: any) => {
  if (e && e.target) {
    form.value.answer = e.target.value
      .replace(/\r\n/g, "\n")
      .replace(/\r/g, "\n");
  }
};

// 处理输入用例的换行转换为 \n
const handleInputChange = (index: number) => {
  const judgeCaseItem = form.value.judgeCase[index];
  if (judgeCaseItem.input) {
    judgeCaseItem.input = judgeCaseItem.input
      .replace(/\r\n/g, "\n")
      .replace(/\r/g, "\n");
  }
};

// 提交
const doSubmit = async () => {
  console.log(form.value);
  // 区分更新还是创建
  if (updatePage) {
    const res = await QuestionControllerService.updateQuestionUsingPost(
      form.value
    );
    if (res.code === 0) {
      ElMessage.success("更新成功");
    } else {
      ElMessage.error("更新失败，" + res.message);
    }
  } else {
    const res = await QuestionControllerService.addQuestionUsingPost(
      form.value
    );
    if (res.code === 0) {
      ElMessage.success("创建成功");
    } else {
      ElMessage.error("创建失败，" + res.message);
    }
  }
};
</script>

<style scoped>
#addQuestionView {
}
</style>
